//
//  ApplyErandsViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-4.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "ApplyErandsViewController.h"
#import "DDEAddProblemViewController.h"
#import "CommonDatePickerViewController.h"
#import "CommonPickerViewController.h"
#import "OtherPickerViewController.h"
#import "MTStatusBarOverlay.h"
#import "SBJson.h"

@interface ApplyErandsViewController () <CommonDatePickerDelegate,CommonPickerDelegate, OtherPickerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *numberLbl;
@property (weak, nonatomic) IBOutlet UILabel *dudaoNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *dudaoNoLbl;
@property (weak, nonatomic) IBOutlet UILabel *dudaoDepLbl;
@property (weak, nonatomic) IBOutlet UILabel *erandReasonLbl;
@property (weak, nonatomic) IBOutlet UILabel *erandTimeLbl;
@property (weak, nonatomic) IBOutlet UILabel *erandEndTimeLbl;
@property (weak, nonatomic) IBOutlet UITextField *erandPlaceLbl;
@property (weak, nonatomic) IBOutlet UILabel *jxsNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *jxsCodeLbl;
@property (weak, nonatomic) IBOutlet UILabel *erandWayLbl;

@property (nonatomic, copy) NSString *piciNumber;

@property (nonatomic, strong) NSMutableDictionary *userDetailInfo; //用户信息
@property (nonatomic, strong) NSMutableArray *sellerList; //经销商信息
@property (nonatomic, strong) NSMutableArray *ccmdArray; //出差目的
@property (nonatomic, strong) NSString *xmmc;//目的其他，事由
@property (nonatomic, strong) CommonPickerViewController *picker;
@property (nonatomic, strong) CommonDatePickerViewController *datePicker;
@property (nonatomic, strong) OtherPickerViewController *otherPicker;

@end

@implementation ApplyErandsViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.networkManager = [[NetworkManager alloc] init];
    
    [self initHUD];

}

//获取当前的批次
- (NSString *)getCurrentPiciNumber {
    NSDate *date = [NSDate date];
    
    long interval = (long)[date timeIntervalSince1970];
    NSString *pici = [NSString stringWithFormat:@"%ld",interval];
//    NSLog(@"*****pici:%@",pici);
    return pici;
}

- (void)savePiciNumber {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dudaoPcDic = [defaults objectForKey:DUDAO_PICI_DEFAULTS_KEY];
    NSMutableDictionary *dudaoPici = [NSMutableDictionary dictionary];
    if (dudaoPcDic != nil) {
        dudaoPici = [NSMutableDictionary dictionaryWithDictionary:dudaoPcDic];
    }
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *strToday = [formatter stringFromDate:date];
    
    NSString *num = self.piciNumber;
    if ([num length] > 3) {
        num = [num substringFromIndex:[num length] - 3];
    }
    if (num != nil) {
        [dudaoPici setValue:num forKey:strToday];
    }
    [defaults setValue:dudaoPici forKey:DUDAO_PICI_DEFAULTS_KEY];
    [defaults synchronize];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"出差申请";
    self.showLeftBtn = YES;
    
    if ([self.erandInfo count] > 0) { //查看或者修改申请
        [self updateViewWithData];
        
        self.showRightBtn = self.canEdit;
        
    } else { //新建申请
        [self updateViewByUserInfo];
        
        self.showRightBtn = YES;
    }
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    
    [self querySellerListByAreaType];
}

//根据职位动态获取出差目的
- (NSMutableArray*) getZhiWeiArray:(NSString*)zhiwei {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@=%@%@%@", SERVER_DOMAIN, @"?ctrl_bussinecs", @"getDictService", @"&input_ostype=ios&input_dtype=CCMD&input_dname=", zhiwei];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *recived = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *recivedStr = [[NSString alloc] initWithData:recived encoding:gbkEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSDictionary *resultDict = [parser objectWithString:recivedStr];
    request = nil;
    parser = nil;
    recivedStr = nil;
    NSDictionary *dataDict = [resultDict objectForKey:@"data"];
    dataDict = [dataDict objectForKey:@"dict"];
    NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:3];
    for (NSDictionary *item in dataDict) {
        NSString *dvalue = [item objectForKey:@"dvalue"];
        [mutableArray addObject:dvalue];
    }
    self.ccmdArray = mutableArray;
    return mutableArray;
}

//根据已有数据刷新界面
- (void)updateViewWithData {
    NSDictionary *data = self.erandInfo;
    NSLog(@"data: %@",data);
    NSString *pici = [data objectForKeyOrNil:@"pc"];
    NSString *name = [data objectForKeyOrNil:@"xm"];
    NSString *gonghao = [data objectForKeyOrNil:@"gh"];
    NSString *zhiwei = [data objectForKeyOrNil:@"zw"];
    
    NSString *reason = [data objectForKeyOrNil:@"ccmd"];
    NSString *destion = [data objectForKeyOrNil:@"ccdd"];
    if ([destion length] == 0) {
        destion = @"";
    }
    NSString *time = [data objectForKeyOrNil:@"ccsj"];
    NSString *timeEnd = [data objectForKeyOrNil:@"ccsjz"];
    NSString *merchantName = [data objectForKeyOrNil:@"jxsmc"];
    NSString *merchantCode = [data objectForKeyOrNil:@"jxsdm"];
    NSString *ccfs = [data objectForKeyOrNil:@"ccfs"];
   
    self.piciNumber = pici;
    self.dudaoNameLbl.text = name;
    self.dudaoNoLbl.text = gonghao;
    self.dudaoDepLbl.text = zhiwei;
    
    self.erandReasonLbl.text = reason;
    self.xmmc = reason;
    self.erandPlaceLbl.text = destion;
    self.erandTimeLbl.text = time;
    self.erandEndTimeLbl.text = timeEnd;
    
    self.erandWayLbl.text = ccfs;
    self.jxsNameLbl.text = merchantName;
    self.jxsCodeLbl.text = merchantCode;
    
    [self getZhiWeiArray:zhiwei];
}

//获取用户详细信息
- (void)getUserDetailInfo {
    UserInfo *user = [UserInfo instance];
    NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:gonghao,@"gh", nil];
    [self.networkManager requestWithMethod:userInfo parameter:param delegate:self];
    [self.HUD show:YES];
}

//根据区域表示查询经销商列表
- (void)querySellerListByAreaType {
    UserInfo *user = [UserInfo instance];
    NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
    NSString *type = [user.info objectForKeyOrNil:@"dqbs"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:gonghao,@"gh", nil];
    RequestMethodId method = sellerInfoA;
    if ([type isEqualToString:@"A"]) {
        method = sellerInfoA;
    } else if ([type isEqualToString:@"B"]) {
        method = sellerInfoB;
    }
    [self.networkManager requestWithMethod:method parameter:param delegate:self];
    [self.HUD show:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightNavItemAction:(id)sender {
    if ([self.erandInfo count] > 0) { //更改
        [self updateErandApply];
    } else { //新建
        [self submitErandApply];
    }
}

//刷新用户相关信息
- (void)updateViewByUserInfo {
    
    //批次号
    self.piciNumber = [self getCurrentPiciNumber];
    
    //督导姓名
    UserInfo *user = [UserInfo instance];
    NSString *name = [user.info objectForKeyOrNil:@"xm"];
    NSString *gh = [user.info objectForKeyOrNil:@"gh"];
    NSString *zhiwei = [user.info objectForKeyOrNil:@"zw"];
    
    self.dudaoNameLbl.text = name;
    self.dudaoNoLbl.text = gh;
    self.dudaoDepLbl.text = zhiwei;
    
}

//获取经销商信息后，赋默认值
- (void)setSellerDefaultValue {
    if ([self.sellerList count] > 0) {
        NSDictionary *firstSeller = [self.sellerList objectAtIndex:0];
        //NSString *name = [firstSeller objectForKeyOrNil:@"jxsmc"];
        //NSString *code = [firstSeller objectForKeyOrNil:@"jxsdm"];
        NSString *name = [firstSeller objectForKeyOrNil:@""];
        NSString *code = [firstSeller objectForKeyOrNil:@""];
        self.jxsNameLbl.text = name;
        self.jxsCodeLbl.text = code;
    }
}

//提交出差申请
- (void)submitErandApply {
    NSString *gh = self.dudaoNoLbl.text;
    NSString *name = self.dudaoNameLbl.text;
    NSString *dept = self.dudaoDepLbl.text;
    NSString *pici = self.piciNumber;
    NSString *reason = self.erandReasonLbl.text;
    NSString *place = self.erandPlaceLbl.text;
    NSString *time = self.erandTimeLbl.text;
    NSString *timeEnd = self.erandEndTimeLbl.text;
    NSString *jxsName = self.jxsNameLbl.text;
    NSString *jxsCode = self.jxsCodeLbl.text;
    NSString *ccfs = self.erandWayLbl.text;
    NSString *xmmc = self.xmmc;
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *ccsjdate = [dateFormat dateFromString:time];
    NSDate *ccsjzdate = [dateFormat dateFromString:timeEnd];
    NSDate *r = [ccsjdate laterDate:ccsjzdate];  //返回较晚的那个日期
    
    if ([reason length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差目的不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([place length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差地点不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([ccfs length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差方式不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
//    else if ([jxsName length] == 0) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
//                                                        message:@"您还没有选择经销商，请选择"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:nil];
//        [alert show];
//    }
    else if(![ccsjdate isEqualToDate:ccsjzdate] && [r isEqualToDate:ccsjdate]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差开始时间不可晚于结束时间"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        
    }
    else {
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gh,@"gh",
                               name,@"xm",
                               pici,@"pc",
                               dept,@"zw",
                               reason,@"ccmd",
                               place,@"ccdd",
                               ccfs,@"ccfs",
                               time,@"ccsj",
                               timeEnd,@"ccsjz",
                               jxsName,@"jxsmc",
                               jxsCode,@"jxsdm",
                               gh,@"czren",
                               xmmc,@"xmmc",
                               nil];

        [self.networkManager requestWithMethod:workApply parameter:param delegate:self];
        [self.HUD show:YES];
        
    }
}

//修改出差申请
- (void)updateErandApply {
    /*
     String request = "input_id=140&input_ccmd=临店&input_ccfs=飞机&input_ccdd=南京&input_jxsmc=奥迪南京4s分店";
     */
    NSDictionary *info = self.erandInfo;
    NSString *erandId = [NSString stringWithFormat:@"%@",[info objectForKeyOrNil:@"id"]];
    NSString *ccmd = self.erandReasonLbl.text;
    NSString *ccfs = self.erandWayLbl.text;
    NSString *ccdd = self.erandPlaceLbl.text;
    NSString *jxsmc = self.jxsNameLbl.text;
    NSString *jxsdm = self.jxsCodeLbl.text;
    NSString *ccsj = self.erandTimeLbl.text;
    NSString *ccsjz = self.erandEndTimeLbl.text;
    NSString *xmmc = self.xmmc;

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *ccsjdate = [dateFormat dateFromString:ccsj];
    NSDate *ccsjzdate = [dateFormat dateFromString:ccsjz];
    NSDate *r = [ccsjdate laterDate:ccsjzdate];  //返回较晚的那个日期
    
   if(![ccsjdate isEqualToDate:ccsjzdate] && [r isEqualToDate:ccsjdate]) {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                       message:@"出差开始时间不可晚于结束时间"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
       [alert show];
       
   } else if ([ccdd length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"出差地点不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               erandId,@"id",
                               ccmd,@"ccmd",
                               ccfs,@"ccfs",
                               ccdd,@"ccdd",
                               jxsmc,@"jxsmc",
                               jxsdm,@"jxsdm",
                               ccsj,@"ccsj",
                               ccsjz,@"ccsjz",
                               xmmc,@"xmmc", nil];
        [self.networkManager requestWithMethod:modifyApply parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

- (void)dismissAlertView {
    
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        int code = [[data objectForKeyOrNil:@"code"] integerValue];
        if (code == 0) { //请求成功
            if ([data count] > 0) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                if (methodId == userInfo) { //获取用户基本信息
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *detailInfo = [dataObject objectForKeyOrNil:@"userInfo"];
                        self.userDetailInfo = [NSMutableDictionary dictionaryWithDictionary:detailInfo];
                        [self updateViewByUserInfo];
                    }
                } else if (methodId == sellerInfoA || methodId == sellerInfoB) {
                    if ([dataObject isKindOfClass:[NSArray class]]) {
                        self.sellerList = [NSMutableArray arrayWithArray:dataObject];
                        if ([self.erandInfo count] == 0) { //新建申请才赋默认值
                            [self setSellerDefaultValue];
                        }
                    }
                    
                } else if (methodId == workApply) {
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        int resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                        if (resultCode > 0) { //提交成功
                            
                            NSString *msg = @"";
                            msg = @"出差申请创建成功！";
                            [self showAlertViewWithMessage:msg];
                            
                            [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                        } else {
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                            message:@"出差申请创建失败，请重试"
                                                                           delegate:nil
                                                                  cancelButtonTitle:@"确定"
                                                                  otherButtonTitles:nil];
                            [alert show];
                        }
                    } else {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:@"出差申请创建失败，请重试"
                                                                       delegate:nil
                                                              cancelButtonTitle:@"确定"
                                                              otherButtonTitles:nil];
                        [alert show];
                    }
                } else if (methodId == modifyApply) { //修改出差申请
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        int resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                        if (resultCode > 0) { //修改成功
                            
                            NSString *msg = @"出差申请修改成功！";
                            [self showAlertViewWithMessage:msg];
                            
                            [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                            
                        } else {
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                            message:@"出差申请修改失败，请重试"
                                                                           delegate:nil
                                                                  cancelButtonTitle:@"确定"
                                                                  otherButtonTitles:nil];
                            [alert show];
                        }
                    } else {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:@"出差申请修改失败，请重试"
                                                                       delegate:nil
                                                              cancelButtonTitle:@"确定"
                                                              otherButtonTitles:nil];
                        [alert show];
                    }
                }
            }
            
            [self.tableView reloadData];
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    if ([msg length] == 0) {
        msg = @"请求失败，请稍后重试";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    
    if (self.canEdit) {
        switch (row) {
            case 0: { //姓名
                
                break;
            }
            case 1: { //工号
                
                break;
            }
            case 2: { //职位
                
                break;
            }
            case 3: { //出差目的
                self.otherPicker = (OtherPickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"OtherPicker"];
                _otherPicker.delegate = self;
                if(self.ccmdArray == nil){
                    [self getZhiWeiArray:self.dudaoDepLbl.text];
                }
//                NSArray *componentData = [NSArray arrayWithObjects:@"临店",@"驻店",@"其他" ,nil];
                _otherPicker.datas = [NSArray arrayWithObjects:self.ccmdArray, nil];
                _otherPicker.view.tag = 20004;
                _otherPicker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
                AppDelegate *app = [AppDelegate sharedDelegate];
                [app.window addSubview:_otherPicker.view];
                break;
            }
            case 4: { //出差方式
                self.picker = (CommonPickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonPicker"];
                _picker.delegate = self;
                NSArray *componentData = [NSArray arrayWithObjects:@"飞机",@"其他" ,nil];
                _picker.datas = [NSArray arrayWithObjects:componentData, nil];
                _picker.view.tag = 20005;
                _picker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
                AppDelegate *app = [AppDelegate sharedDelegate];
                [app.window addSubview:_picker.view];
                break;
            }
            case 5: { //出差开始时间
                self.datePicker = (CommonDatePickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonDatePicker"];
                _datePicker.delegate = self;
                _datePicker.view.tag = 20006;
                
                AppDelegate *app = [AppDelegate sharedDelegate];
                _datePicker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame),
                                                    CGRectGetHeight(self.view.bounds));
                
                [app.window addSubview:_datePicker.view];
                
                break;
            }
            case 6: { //出差结束时间
                self.datePicker = (CommonDatePickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonDatePicker"];
                _datePicker.delegate = self;
                _datePicker.view.tag = 20009;
                
                AppDelegate *app = [AppDelegate sharedDelegate];
                _datePicker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame),
                                                    CGRectGetHeight(self.view.bounds));
                
                [app.window addSubview:_datePicker.view];
                
                break;
            }
            case 7: { //出差地点
                
                break;
            }
            case 8: { //经销商名称
                self.picker = (CommonPickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonPicker"];
                _picker.delegate = self;
                NSMutableArray *sellerNames = [NSMutableArray array];
                if ([self.sellerList count] > 0) {
                    for (NSDictionary *seller in self.sellerList) {
                        NSString *name = [seller objectForKeyOrNil:@"jxsmc"];
                        if (name != nil) {
                            [sellerNames addObject:name];
                        }
                    }
                }
                _picker.datas = [NSArray arrayWithObjects:sellerNames, nil];
                _picker.view.tag = 20007;
                _picker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
                AppDelegate *app = [AppDelegate sharedDelegate];
                [app.window addSubview:_picker.view];
                break;
            }
            case 9: { //经销商代码
                break;
            }
            
            default:
                break;
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (self.canEdit) {
        if (textField.inputAccessoryView == nil) {
            UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
            [topView setBarStyle:UIBarStyleDefault];
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(320-42, 3, 40, 26);
            [button setTitle:@"完成" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [button addTarget:self action:@selector(dismissKeyBoard:) forControlEvents:UIControlEventTouchUpInside];
            
            [topView addSubview:button];
            
            [textField setInputAccessoryView:topView];
        }
        return YES;
    } else {
        return NO;
    }
}

- (void)dismissKeyBoard:(id)sender {
    [self.view endEditing:YES];
}

#pragma mark - CommonDatePickerDelegate
- (void)picker:(CommonDatePickerViewController *)picker didSelectedDate:(NSDate *)date {
    NSInteger tag = picker.view.tag;
    if (date != nil && tag == 20006) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [formatter stringFromDate:date];
        self.erandTimeLbl.text = strDate;
    } else if(date != nil && tag == 20009){
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [formatter stringFromDate:date];
        self.erandEndTimeLbl.text = strDate;
    }
}

#pragma mark - CommonPickerDelegate
- (void)picker:(CommonPickerViewController *)picker didSelectedItemIndexSet:(NSDictionary *)selectedItems {
    NSInteger index = [[selectedItems objectForKey:[NSNumber numberWithInt:0]] integerValue];
    
    NSInteger tag = picker.view.tag;
    if (tag == 20004) { //出差目的
        if(self.ccmdArray == nil){
            [self getZhiWeiArray:self.dudaoDepLbl.text];
        }
        NSArray *tiles = [NSArray arrayWithObjects:self.ccmdArray ,nil];
        NSString *other = [[tiles objectAtIndex:0] objectAtIndex:index];
        if([other isEqualToString:@"其他"]){
            NSString *otherText = [self.otherPicker getOther];
            self.erandReasonLbl.text = other;
            self.xmmc = otherText;
//            self.erandPlaceLbl.text = otherText;
        }else{
            self.erandReasonLbl.text = other;
//            self.erandPlaceLbl.text = other;
        }
    } else if (tag == 20005) {
        NSArray *tiles = [NSArray arrayWithObjects:@"飞机",@"其他" ,nil];
        self.erandWayLbl.text = [tiles objectAtIndex:index];
    } else if (tag == 20007 || tag == 20008) { //经销商名称/代码
        if ([self.sellerList count] > index) {
            NSDictionary *seller = [self.sellerList objectAtIndex:index];
            NSString *name = [seller objectForKeyOrNil:@"jxsmc"];
            NSString *code = [seller objectForKeyOrNil:@"jxsdm"];
            self.jxsNameLbl.text = name;
            self.jxsCodeLbl.text = code;
        }
    }
}

@end
